/**
 * 打卷序时表
 */

const menuId = 403;
const PRINT_TEMPLATE_NAME = 'cpRepository.cpt';
//库存表
$(function () {

    $('#A').window('close');

    getreportStartDate();

    initKendoUiGrid();
    btn_refresh();

});

/**
 * 将数组去重
 * @param arr
 * @param attribute
 * @returns {[]}
 */
function unique(arr, attribute) {
    let new_arr = [];
    let json_arr = [];
    for (let i = 0; i < arr.length; i++) {
        if (new_arr.indexOf(arr[i][attribute]) == -1) {
            new_arr.push(arr[i][attribute]);
            json_arr.push(arr[i]);
        }
    }
    return json_arr;
}


//通过JS配置  生成前端报表页面
function initKendoUiGrid(data) {

    var fhbarcode = new kendo.data.DataSource({data: []});
    var dyename = new kendo.data.DataSource({data: []});
    var clientname = new kendo.data.DataSource({data: []});
    var pinming = new kendo.data.DataSource({data: []});
    var whitegg = new kendo.data.DataSource({data: []});
    var ylgg = new kendo.data.DataSource({data: []});
    var ps = new kendo.data.DataSource({data: []});
    var qty = new kendo.data.DataSource({data: []});
    var bill_date = new kendo.data.DataSource({data: []});

    var dataSource = new kendo.data.DataSource({
        data: data,

        schema: {
            model: {
                fields: {
                    ps: {type: "number"},
                    qty: {type: "number"},

                }
            }
        },
        aggregate: [
            {field: "ps", aggregate: "sum"},
            {field: "qty", aggregate: "sum"},

        ],

        change: function (e) {
            //获取过滤条件
            let filtrer = this.filter();
            //获取所有数据
            let allData = this.data();
            //进行过滤条件的筛选
            let query = new kendo.data.Query(allData);
            //获取过过滤后的数据
            let data = query.filter(filtrer).data;
            fhbarcode.data(unique(data, 'fhbarcode'));
            dyename.data(unique(data, 'dyename'));
            clientname.data(unique(data, 'clientname'));
            pinming.data(unique(data, 'pinming'));
            whitegg.data(unique(data, 'whitegg'));
            ylgg.data(unique(data, 'ylgg'));
            bill_date.data(unique(data, 'bill_date'));

            ps.data(unique(data, 'ps'));
            qty.data(unique(data, 'qty'));

        },
        pageSize: 200,
        requestStart: function (e) {
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text == '查询' || (btn.linkbutton('options').text == '过滤')) {
                    btn.linkbutton('disable')
                }
            })
        },
        requestEnd: function (e) {
            let response = e.response;
            if (response && response['message']) {
                $.messager.show({title: '提示', msg: response['message']})
            }
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text == '查询' || (btn.linkbutton('options').text == '过滤')) {
                    btn.linkbutton('enable')
                }
            })
        }
    });
    var grid = $("#bill").kendoGrid({
        sortable: true,
        resizable: true,
        selectable: "multiple row",
        editable: false,
        filterable: true,
        title: "报表",
        columnMenu: {
            sortable: true
        },
        excel: {
            fileName: "计划单序时表.xlsx",
            proxyURL: "",
            allPages: true,
            filterable: true
        },
        pageable: {
            pageSize: 200
        },
        dataSource: dataSource,
        columns: [
            {
                field: "", title: "序号", width: 30,
                template: "<span class='row_number'></span>", width: 40
            },

            {
                field: 'fhbarcode',
                title: '发货单号',
                footerTemplate: '总计:',
                width: 80,
                filterable: {multi: true, search: true, dataSource: fhbarcode},
                footerAttributes: {style: "text-align:right;"},
                attributes: {style: "text-align:center;white-space:nowrap;text-overflow:ellipsis;"},
                headerAttributes: {style: 'text-align:center;'}
            },
            {
                field: "dyename",
                title: '染厂名称',
                width: 100,
                filterable: {multi: true, search: true, dataSource: dyename},
                attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: "clientname",
                title: '客户名称',
                width: 100,
                filterable: {multi: true, search: true, dataSource: clientname},
                attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'pinming',
                title: '品名',
                width: 100,
                filterable: {multi: true, search: true, dataSource: pinming},
                attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'whitegg',
                title: '白坯规格',
                width: 100,
                filterable: {multi: true, search: true, dataSource: whitegg},
                attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },

            {
                field: 'ylgg',
                title: '原料规格',
                width: 100,
                filterable: {multi: true, search: true, dataSource: ylgg},
                attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },

            {
                field: 'ps',
                title: '发货匹数',
                width: 80,
                template: item => item['ps'] ? parseFloat(item['ps']).toFixed(0) : '',
                format: "{0:n1}",
                footerTemplate: '#=kendo.format("{0:n1}",sum)#',
                footerAttributes: {style: "text-align:right;"},
                attributes: {style: "text-align:right;",'class': 'kendo-custum-number'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },
            {
                field: 'qty',
                title: '发货重量',
                width: 100,
                template: item => item['qty'] ? parseFloat(item['qty']).toFixed(1) : '',
                format: "{0:n1}",
                footerTemplate: '#=kendo.format("{0:n1}",sum)#',
                footerAttributes: {style: "text-align:right;"},
                attributes: {style: "text-align:right;",'class': 'kendo-custum-number'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },

            {
                field: "bill_date",
                title: '发货日期',
                width: 150,
                filterable: {multi: true, search: true, dataSource: bill_date},
                attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
                headerAttributes: {style: 'text-align:center;margin-right: 2px;'}
            },

        ],
        reorderable: true,
        height: '99%',
        dataBound: function () {
            var rows = this.items();
            $(rows).each(function () {
                var index = $(this).index() + 1;
                var rowLabel = $(this).find(".row_number");
                $(rowLabel).html(index);
            });
        },
    });
    var grid01 = $("#bill").data("kendoGrid");
    //双击事件
    grid.on('dblclick', 'tr', function () {
        //  代码
        var kGrid = $("#bill").data("kendoGrid");
        var row = kGrid.select();
        var dataItem = kGrid.dataItem(row);
        var id = dataItem['id'];
        window.parent.addTab('打印发货单', 'printfhd.html?id=' + id);
    });
    //右击事件
    grid.on('contextmenu', 'tr', function (e) {
        e.preventDefault();
        //  代码

    });
    //  单击事件
    grid.on('click', 'tr', function () {
        //  代码

    });
}


//刷新
function btn_refresh() {
    var kGrid = $("#bill").data("kendoGrid");

    var data1 = $('#start').datebox('getValue') + ' 00:00:00';
    var data2 = $('#end').datebox('getValue')+ ' 23:59:59';
    console.log(strLin + '/fh/fhchro/'+ data1 + "/" + data2);
    $.ajax({
        url: strLin + '/fh/fhchro/'+ data1 + "/" + data2 ,
        type: 'get',
        dataType: 'json',
        success: function (cdata) {
            let data=cdata.data;
            console.log(data);
            kGrid.dataSource.data(data);
        }

    });
}

//打印
function btn_print() {
    let kGrid = $("#bill").data("kendoGrid");
    if (kGrid == undefined) {
        $.messager.alert('提示', '网格组件异常！请刷新重试！');
        return;
    }
    let filtrer = kGrid.dataSource.filter();
    let allData = kGrid.dataSource.data();
    let query = new kendo.data.Query(allData);
    let data = query.filter(filtrer).data;
    if (data != undefined && data.length > 0) {
        let arr = [];
        for (let i = 0; i < data.length; i++) {
            let item = data[i]['planId'];
            if (item) arr.push(item);
        }
        if (arr.length <= 0) return;
        let reportlets = [];
        let printTemplate = {};
        printTemplate.ids = arr.join(',');
        printTemplate.reportlet = PRINT_TEMPLATE_NAME;
        reportlets.push(printTemplate);
        if (reportlets.length <= 0) {
            $.messager.show({title: '提示', msg: '没有明细！无法打印！'});
            return;
        }
        let config = {
            url: "ReportServer",
            isPopUp: false,
            data: {
                reportlets: reportlets
            }
        };
        FR.doURLPDFPrint(config);
    }
}

//导出
function btn_export() {
    let kGrid = $("#bill").data("kendoGrid");
    if (kGrid == undefined) {
        $.messager.alert('提示', '网格组件异常！请刷新重试！');
        return;
    }
    kGrid.saveAsExcel();
}

//重置
function btn_reset() {
    $.messager.show('提示', '该页面暂无chongzh业务！');
}

//  清除过滤
function btn_cancel_filter() {
    let kGrid = $("#bill").data("kendoGrid");
    if (kGrid != undefined) {
        kGrid.dataSource.filter({});
    }
}


//获取日期
function getDate(param) {
    if (isNaN(param)) {
        param = 0;
    }
    var curDate = new Date();
    var newDate = new Date(curDate);
    newDate.setDate(curDate.getDate() + param);
    var year = newDate.getFullYear();
    var month = newDate.getMonth() + 1 < 10 ? '0' + (newDate.getMonth() + 1) : newDate.getMonth() + 1;
    var date = newDate.getDate() < 10 ? '0' + newDate.getDate() : newDate.getDate();
    var separator = '-';
    return year + separator + month + separator + date;
}

//关闭当前标签页事件
function closeTab() {
    window.parent.closeTab();
}

/***************************************************************************/
//双击主页面打开弹出页面

//根据细码单号获取对应的所有打卷数据
function getJRKDetail(barCode) {
    $.ajax({
        url: strLin + '/jrk/xmd/'+barCode,

        type: 'get',
        dataType: 'json',
        success: function (cdata) {
            let data=cdata.data;
            m_DTRK=data[0].b_rkdate;
            m_KH=data[0].b_id;
            console.log(m_DTRK);
            $('#rkdetai').datagrid('loadData', data);

        }, complete: function (XMLHttpRequest, textStatus) {
            console.log("进入到complete");
        }

    })
}
//合计
function  getsum03() {
    //扫码发货页面网格数据汇总
    $('#rkdetai').datagrid({
        showFooter: true,
        onLoadSuccess: function (data) {
            data = data.rows;
            var qty = 0;
            var ps=0;

            for (let i = 0; i < data.length; i++) {
                qty += data[i].b_gj ? parseFloat(data[i].b_gj) : 0;
                ps =i+1;
            }
            console.log(qty);
            $(this).datagrid('reloadFooter', [{
                b_id: '合计',
                b_gj: qty.toFixed(1),
                b_aorb: ps,
            }])
        }
    });


}

//退出
function Aclose() {
    var data=[];
    $('#rkdetai').datagrid('loadData', data);
    getsum03();
    $("#AB").textbox('setValue', '');
    $("#ZL").textbox('setValue', '');
    $("#indow").textbox('setValue', '');
    m_BarCode=0;
    $('#A').window('close');
}

//修改入库数据
function updateJRKXMD() {
    var currentRow = $("#rkdetai").datagrid("getSelected");//获得选中行的信息
    if (currentRow != undefined) {
        if (currentRow.isfh=='已发货'){
            $.messager.alert('确认', '已发货数据不允许修改!');
            return;
        }else {
            // var rows = $('#rkdetai').datagrid('getRows');//获得所有行
            var c = $("#rkdetai").datagrid('getSelected');//选中的行
            var a = $('#rkdetai').datagrid('getRowIndex', c);//获取行号

            $("#indow").textbox('setValue', a + 1);
            $("#AB").textbox('setValue', currentRow.b_aorb);
            $("#ZL").textbox('setValue', currentRow.b_gj);
            m_Itemid=currentRow.b_itemid;
        }
    } else {
        $.messager.alert('确认', '当前没有选中数据!');
        return;
    }

}

//新增一条打卷数据
function addJRKDetail() {
    var rows = $('#rkdetai').datagrid('getRows');//获得所有行
    var d=rows.length+1 ;
    $("#indow").textbox('setValue', d);
    $("#AB").textbox('setValue', '');
    $("#ZL").textbox('setValue', '');
    m_Itemid=0;
}

//删除一条选中的明细  已发货数据不允许删除  OK
function deteleJRKDetail() {
    var currentRow = $("#rkdetai").datagrid("getSelected");//获得选中行的信息
    if (currentRow != undefined) {
        if (currentRow.isfh=='已发货'){
            $.messager.alert('确认', '已发货数据不允许删除!');
            return;
        }else {
            $.messager.defaults = {ok: "确定", cancel: "取消", width: 250, closable: false};
            $.messager.confirm('确认', '您确认要删除当前单据吗？', function (r) {
                if (r) {
                    m_Itemid = currentRow.b_itemid;

                    var str={b_itemid:m_Itemid};
                    console.log(strLin + '/jrk/delete/'+m_Itemid);

                    $.ajax({
                        url: strLin + '/jrk/delete/'+m_Itemid,
                        type: 'delete',
                        dataType: 'json',
                        // data: JSON.stringify(str),
                        contentType: "application/json;charset=UTF-8",
                        success: function (data) {
                            console.log(data);
                            // alert('删除完成！');
                            getJRKDetail(m_BarCode);
                            getsum03();
                        }
                    });
                }
            });
        }
    } else {
        $.messager.alert('确认', '当前没有选中数据!');
        return;
    }

}

function SaveJRKDetail() {
    //打卷表数据主键大于0表示是修改，等于零是新增
    if (m_Itemid>0){
        var GJ = $("#ZL").textbox('getValue');
        var ABM = $("#AB").textbox('getValue');

        var str={b_itemid:m_Itemid,b_gj:GJ,b_aorb:ABM};
        console.log(str);
        $.ajax({
            url: strLin + '/jrk/updateSelective',
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify(str),
            contentType: "application/json;charset=UTF-8",
            success: function (data) {
                $("#indow").textbox('setValue', '');
                $("#AB").textbox('setValue', '');
                $("#ZL").textbox('setValue', '');
                m_Itemid=0;
                getJRKDetail(m_BarCode);
                getsum03();
            }
        });
    }else{

        //新增
        var GJ1 = $("#ZL").textbox('getValue');
        var ABM1 = $("#AB").textbox('getValue');
        var etime = new Date();
        var m_date = format(etime);

        var str1={b_id:m_KH,b_gj:GJ1,b_aorb:ABM1,b_date:m_date,b_dtrk:m_DTRK,b_barcode:m_BarCode};
        console.log(str1);
        $.ajax({
            url: strLin + '/jrk/insert',
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify(str1),
            contentType: "application/json;charset=UTF-8",
            success: function (data) {
                $("#indow").textbox('setValue', '');
                $("#AB").textbox('setValue', '');
                $("#ZL").textbox('setValue', '');
                m_Itemid=0;
                getJRKDetail(m_BarCode);
                getsum03();
            }
        });
    }




}

/*****************************************************/

/*设置时间格式*/
function add0(m) {
    return m < 10 ? '0' + m : m
}

function format(shijianchuo) {
    //shijianchuo是整数，否则要parseInt转换
    var time = new Date(shijianchuo);
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s);
}

/****************************************************/


//获取报表对应的起始日期
function getreportStartDate() {
    $.ajax({
        url: strLin + '/configAll/all',
        type: 'get',
        dataType: 'json',
        success: function (cdata) {
            let  data=cdata.data;
            console.log(data);
            data1=data.filter(item=>item.config_name==="发货序时表_pc");
            var starDate=getDay(-data1[0].value_num);
            console.log(starDate);
            $("#start").datebox("setValue", starDate);
            btn_refresh();

        }
    })
}